import React, { useRef, useState } from 'react';
import { PageContainer , ProColumns, ActionType, ProTable,
  ModalForm, ProFormText, ProFormSelect
} from '@ant-design/pro-components';
import { userList, roleEffectlist, updateStatus, roleChange, userCreate } from '@/services/user'
import { Button, message, Popconfirm } from 'antd';
import { useRequest } from 'ahooks';
import { PlusOutlined } from '@ant-design/icons';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>()
  const columns: ProColumns<any>[] = [
    {
      title: 'id',
      dataIndex: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '用户名',
      dataIndex: 'userName',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
    },
    {
      title: '角色',
      dataIndex: 'roleName',
    },
    {
      title: '状态',
      render: (text, record) => {
        if (record.deleted == false) {
          return '启用'
        } else {
          return '停用'
        }
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (text, record) => [<Popconfirm
        title={`确认${record.deleted ? '启用' : '停用'}？`}
        key='1'
        onConfirm={() => {
          doUpdate({ id: record.id, status: !record.deleted })
        }}
        onCancel={() => { }}
        okText="确定"
        cancelText="取消"
      >
        <Button
          danger={!record.deleted}
          type="primary"
          size='small'
        >
          {
            record.deleted ? '启用' : '停用'
          }
        </Button>
      </Popconfirm>,
      <Button
        key='2'
        type="primary"
        size='small'
        onClick={() => {
          setId(record.id)
          setVisible(true)
        }}
      >角色分配</Button>
      ]
    }
  ]
  /**
   * 获取角色
   */
  const [visible, setVisible] = useState(false)
  const [roleList, setroleList] = useState([])
  useRequest(roleEffectlist, {
    onSuccess: (res) => {
      setroleList(res.map((item: any) => ({
        label: item.roleName,
        value: item.id
      })))
      
    },
  })
  /**
   * 更新用户状态
   */
  const { run: doUpdate } = useRequest(updateStatus, {
    manual: true,
    onSuccess: () => {
      message.success('更新成功')
      actionRef.current?.reload()
    }
  })
  /**
   * 新增用户
   */
  const { run: doCreate } = useRequest(userCreate, {
    manual: true,
    onSuccess: () => {
      message.success('新增成功')
      actionRef.current?.reload()
    }
  })
  /**
   * 更新用户角色
   */
  const [id, setId] = useState()
  const { run: doChange } = useRequest(roleChange, {
    manual: true,
    onSuccess: () => {
      message.success('修改成功')
      actionRef.current?.reload()
    }
  })
  
  return (
    <PageContainer header={{breadcrumb: {}}}>
      <ProTable<any, API.PageParams>
        headerTitle='用户列表'
        actionRef={actionRef}
        rowKey="id"
        size='large'
        search={{
          labelWidth: 100,
        }}
        toolBarRender={() => [
          <ModalForm
            width='420px'
            trigger={
              <Button type="primary">
                <PlusOutlined />
                添加账号
              </Button>
            }
            modalProps={{
              destroyOnClose: true,
              centered: true
            }}
            onFinish={async (values: any) => {
              doCreate(values)
              return true;
            }}
          >
            <ProFormText
              label='姓名'
              name='name'
              rules={[{
                required: true,
                message: '请输入姓名'
              }]}
            />
            <ProFormText
              label='联系方式'
              fieldProps={{
                maxLength: 11
              }}
              name='mobile'
              rules={[
                {
                  required: true,
                  message: '请输入联系方式'
                },
                {
                  message: '请输入正确的手机号码',
                  validator(_, value) {
                    if (value && !(/^1[3|4|5|7|8][0-9]{9}$/.test(value))) {
                      return Promise.reject(new Error('错误'))
                    }
                    return Promise.resolve()
                  },
                },
              ]}
            />
            <ProFormText
              label='用户名'
              name='userName'
              rules={[{
                required: true,
                message: '请输入用户名'
              }]}
            />
            <ProFormText.Password
              label='密码'
              name='password'
              rules={[
                {
                  required: true,
                  message: '请输入密码'
                },
                {
                  max: 20,
                  message: '密码为6-20位字符'
                },
                {
                  min: 6,
                  message: '密码为6-20位字符'
                }
              ]}
            />
            <ProFormSelect
              label='角色选择'
              name='roleId'
              options={roleList}
              rules={[{
                required: true,
                message: '请选择角色'
              }]}
            />

          </ModalForm>,
        ]}
        pagination={false}
        request={async (PageParams) => {
          const res = await userList({ ...PageParams, pageIndex: PageParams.current })
          return {
            data: res,
            success: true,
          }
        }}
        columns={columns}
      />
      <ModalForm
        width='420px'
        visible={visible}
        title="选择角色"
        onVisibleChange={(visible) => {
          setVisible(visible)
        }}
        modalProps={{
          destroyOnClose: true,
          centered: true
        }}
        onFinish={async (values: any) => {
          doChange({ ...values, id })
          return true
        }}
      >
        <ProFormSelect
          label='角色选择'
          name='roleId'
          options={roleList}
          rules={[{
            required: true,
            message: '请选择角色'
          }]}
        />
      </ModalForm>
      
    </PageContainer>
  );
};

export default TableList;
